const importLazy = require('import-lazy')(require);

const Okapi = importLazy('../../okapi');
const AuthService = importLazy('../../okapi/auth-service');
const { okapiRequired, tenantRequired } = importLazy('../common-options');

function addUserCommand(argv) {
  const okapi = new Okapi(argv.okapi, argv.tenant, argv.pathapi);
  const authService = new AuthService(okapi);

  const data = {
    'active': true,
    'barcode': argv.username,
    'personal': {
      'lastName': argv.username
    },
    'username': argv.loginname
  };

  return authService.addUSer(data)
    .then((res) => {
      // 新用户注册密码
      const param = {
        userId: res.id,
        password: argv.password
      };
      // 新用户注册权限
      const defaultAssign = {
        'userId': res.id,
        'permissions': [
          'users.all',
          'perms.all',
          'login.all',
          'users-bl.all'
        ]
      };
      authService.userCredentials(param).then(() => {
        authService.userDefaultAssign(defaultAssign).then(() => {
          console.log(`User ${res.username} Add successfully on Okapi ${argv.okapi} and Password is ${argv.password}`);
        });
      });
    })
    .catch((err) => {
      console.log('Error add User.', err);
    });
}

module.exports = {
  command: 'adduser <loginname> <password> <username>',
  describe: 'Add User into an Okapi tenant environment',
  builder: (yargs) => {
    yargs
      .option('loginname', {
        describe: 'user login name',
        type: 'string',
      })
      .option('password', {
        describe: 'user login password',
        type: 'string',
      })
      .option('username', {
        describe: 'user personal name',
        type: 'string',
      })
      .options(Object.assign({}, okapiRequired, tenantRequired))
      .demandOption(['okapi', 'tenant'], 'Okapi and tenant must be available (via options, config file, or env var) in order to add user.')
      .example('$0 okapi adduser admin 111111 管理员 --okapi http://localhost:9130 --tenant diku', 'Add user admin into tenant diku')
      .example('$0 okapi adduser admin 111111 管理员', 'Add User with okapi and tenant already set');
  },
  handler: addUserCommand,
};
